package com.example.app2024.boardcast;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app2024.R;

import java.util.Date;

/**
 * 广播分静态注册与动态注册
 * 8.0 之后对静态有了限制
 */
public class myboardcastActivity extends AppCompatActivity
{
      public static final String MY_ACTION = "com.example.zxj";
      MyReceiver receiver;

      @Override
      protected void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            EdgeToEdge.enable(this);
            setContentView(R.layout.activity_myboardcast);
            ViewCompat.setOnApplyWindowInsetsListener(
                    findViewById(R.id.main), (v, insets) -> {
                          Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                          v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
                          return insets;
                    });



            // 新建广播接收器
            receiver = new MyReceiver();

            // 注册广播接收器

            // 为广播接收器添加Action
            IntentFilter intentFilter = new IntentFilter();
           intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
           intentFilter.addAction(MY_ACTION );

            // 注册广播接收器 这里需要最小api 为26
            registerReceiver(receiver, intentFilter , RECEIVER_EXPORTED);

      }

      @Override
      protected void onDestroy()
      {
            super.onDestroy();
            if (receiver != null        )
            {
                  unregisterReceiver(receiver);
                  Log.i("TAG", "onDestroy: 退出广播监听");
            }

      }

      public void docasttime(View view)
      {
            // 新建广播
            Intent intent = new Intent(MY_ACTION);
            // 放入广播要携带的数据
            intent.putExtra("myzxj", new Date().getTime()+"");
            sendBroadcast(intent);
      }
}